import json
from datetime import datetime

from fastapi import APIRouter
from pydantic import BaseModel
from starlette.requests import Request

from business.base.AjaxJson import AjaxJson
from utils.MySqlUtil import MySqlUtil
from utils.snowflakeId.xuehuaid import IdWorker

router = APIRouter(
    prefix="/goods",
    tags=["goods"],
    responses={404: {"description": "Not found"}},
)


class PageObj(BaseModel):
    pageNumber: int = None
    pageSize: int = None


class Goods(BaseModel):
    goodsName: str = None
    imgUrl: str = None
    specification: str = None
    nature: str = None
    description: str = None
    price: str = None
    repertory: str = None
    id: str = None
    boutique: str = None
    classify: str = None


@router.post("/findGoodsList")
async def findGoodsList(page: PageObj):
    pageNumber = 1 if page.pageNumber == 0 else page.pageNumber
    pageSize = page.pageSize
    j = AjaxJson()
    j.code = 'failure'
    j.msg = '获取分页数据失败'
    sql = 'SELECT * FROM goods limit %s,%s'
    db = MySqlUtil()
    data = db.query(sql, ((pageNumber - 1) * pageSize, pageSize))
    count = db.get_count('SELECT count(1) FROM goods', None)
    result = {
        "goodsList": data,
        "count": count
    }
    j.data = result
    j.code = 'success'
    j.msg = '获取分页数据成功'
    return j


@router.post("/addOrUpdateGoods")
async def addOrUpdateGoods(goods: Goods):
    j = AjaxJson()
    j.code = 'failure'
    j.msg = '操作失败'
    db = MySqlUtil()
    goodsId = goods.id
    if goodsId is None or goodsId == '':  # 新增
        goodsId = IdWorker().sequence_generator()
        goods_dict = dict(goods)
        goods_dict['id'] = goodsId
        goods_dict['create_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        goods_dict['create_user'] = 'admin'
        sql = 'INSERT INTO goods(id, create_date, create_user, update_date, update_user, boutique, classify, ' \
              'description, goods_name, img_url, nature, price, repertory, specification) VALUES (%(id)s, ' \
              '%(create_date)s, %(create_user)s, NULL, NULL, %(boutique)s, %(classify)s, ' \
              '%(description)s,  %(goodsName)s, %(imgUrl)s, %(nature)s,%(price)s, %(repertory)s,  %(specification)s) '
        db.execute(sql, goods_dict)
    else:  # 更新
        sql = 'UPDATE goods SET update_date = %(update_date)s, update_user = %(update_user)s, boutique = %(' \
              'boutique)s, classify = %(classify)s, description = %(description)s, goods_name = %(goodsName)s, ' \
              'img_url = %(imgUrl)s, nature =%(nature)s, price = %(price)s, repertory = %(repertory)s, specification ' \
              '= %(specification)s WHERE id = %(id)s '
        goods_dict = dict(goods)
        goods_dict['update_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        goods_dict['update_user'] = 'admin'
        db.execute(sql, goods_dict)
    j.code = 'success'
    j.msg = '操作成功'
    return j


@router.get("/getGoods")
async def getGoods(goods_id: str):
    j = AjaxJson()
    j.code = 'failure'
    j.msg = '获取商品信息失败'
    sql = 'SELECT * FROM goods t WHERE t.id = %s'
    db = MySqlUtil()
    result = db.query(sql, goods_id)
    j.code = 'success'
    j.msg = '获取商品信息成功'
    if len(result) > 0:
        j.data = result[0]
    else:
        j.data = {}
    return j


@router.post("/deleteGoods")
async def deleteGoods(request: Request):
    """
    删除要删除对应的图片文件，就不在这里实现了，还是在java中处理，图片放在java执行环境的相对路径中，这里不太好处理
    :param request:
    :return:
    """
    request_body = await request.json()
    goods_id = request_body['goods_id']
    print(goods_id)
    j = AjaxJson()
    j.code = 'failure'
    j.msg = '删除商品失败'
    return j
